<template>
  <div class="post-list" >
     <mu-refresh-control :refreshing="refreshing" :trigger="trigger" @refresh="refresh"/>
     <post-item  :post="post"  v-for="post in posts" :key="post.id" @click.native="openPost(post)"></post-item>
     <mu-infinite-scroll :scroller="trigger" :loading="loading" @load="getNext"/>
  </div>
</template>
<script>
import postItem from './postItem'
import {mapGetters} from 'vuex'
export default {
  components: {
    postItem
  },
  computed: mapGetters({
    posts: 'getPosts',
    tagSlug: 'getTagSlug'
  }),
  data () {
    return {
      pagination: {page: 1, limit: 4, pages: 0, total: 0, next: 0, pre: 0},
      loading: false,
      refreshing: false,
      trigger: null
    }
  },
  mounted () {
    this.trigger = this.$el
    if (!this.posts || this.posts.length === 0) {
      this.getData(this.pagination.page)
    }
  },
  watch: {
    tagSlug () {
      this.getData(1)
      this.$el.scrollTop = 0
    }
  },
  methods: {
    refresh () {
      this.refreshing = true
      this.getData(1)
    },
    getData (page) {
      let filter = {}
      if (this.tagSlug !== 'all') {
        filter = `tags:[${this.tagSlug}]`
      } else {
        filter = null
      }
      this.$api.post.getPosts({limit: this.pagination.limit, page, filter})
    .then(res => {
      if (page === 1) {
        this.$store.commit('setPosts', res.posts)
      } else {
        this.posts.push(...res.posts)
      }
      this.pagination = res.meta.pagination
      this.loading = false
      this.refreshing = false
    })
    },
    getNext () {
      this.loading = true
      if (this.pagination.next) {
        this.getData(this.pagination.next)
      } else {
        this.loading = false
      }
    },
    openPost (post) {
      this.$router.push({name: 'postDetails', params: {id: post.id}})
      this.$store.commit('setPost', post)
    }
  }
}
</script>
<style  scoped lang="less">
.post-list{
    margin-left: auto;
    margin-right: auto;
    overflow-x: hidden; overflow-y: auto; 
   @media (min-width: 768px) {
      padding-left: 20%;
      padding-right: 20%;
    }
    @media (max-width: 480px) {
    }
}
</style>
